package com.hui.platform.falseworkapi.common.security.configurer;

import com.hui.platform.falseworkapi.common.security.base.IBasicHttpSecurityConfigurer;
import com.hui.platform.falseworkapi.common.security.base.ISecurityIgnoredUris;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 基本忽略路径 安全路径配置
 *
 * @author Peng
 * @date 2019/12/12
 */
@Component
public class BaseIgnoreBasicHttpSecurityConfigurer implements IBasicHttpSecurityConfigurer, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public int order() {
        return MAX_ORDER - 100;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        String[] basicStaticUrls = {
                "/",
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js",
                "/webjars/**",
                "/static/**"
        };

        //需要转一下ArraysList
        List<String> list = new ArrayList<>(Arrays.asList(basicStaticUrls));
        //拓展静态资源Url（从ApplicationContext获取相关的Bean）
        Map<String, ISecurityIgnoredUris> beansOfType = applicationContext.getBeansOfType(ISecurityIgnoredUris.class);
        //从Beans中获取额外的Urls
        beansOfType.forEach((k, v) -> list.addAll(v.getIgnoredUris()));
        //静态资源
        String[] patterns = list.toArray(new String[]{});

        //规则
        //选择匹配器
        http.requestMatchers().antMatchers(patterns);
        //权限解决器
        http.authorizeRequests().antMatchers(patterns).permitAll();
    }
}
